/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2024-2024. All rights reserved.
 */

import { TaskDirectedAcyclicGraph } from '../../../../src/base/internal/task/core/task-directed-acyclic-graph';

describe('Test dag circle check', () => {
  const dag = new TaskDirectedAcyclicGraph();

  /**
   * task1->task1
   */
  test('test circle check1', () => {
    dag.clear();
    dag.addEdge('task1', 'task1');
    const {hasCircle, circlePath} = dag.checkCircle();
    expect(hasCircle).toBe(true);
    expect(circlePath.join('->')).toEqual('task1->task1');
  });

  /**
   * task1->task2->task3->task2
   * task3->task1
   */
  test('test circle check23', () => {
    dag.clear();
    dag.addEdge('task1', 'task2');
    dag.addEdge('task2', 'task3');
    dag.addEdge('task3', 'task2');
    dag.addEdge('task3', 'task1');
    const {hasCircle, circlePath} = dag.checkCircle();
    expect(hasCircle).toBe(true);
    expect(circlePath.join('->')).toEqual('task1->task2->task3->task2');
  });

  /**
   * task1->task2->task3->task1
   */
  test('test circle check2', () => {
    dag.clear();
    dag.addEdge('task1', 'task2');
    dag.addEdge('task2', 'task3');
    dag.addEdge('task3', 'task1');
    const {hasCircle, circlePath} = dag.checkCircle();
    expect(hasCircle).toBe(true);
    expect(circlePath.join('->')).toEqual('task1->task2->task3->task1');
  });

  /**
   * task1->task2->task3
   * task4->task5->task3
   */
  test('test circle check3', () => {
    dag.clear();
    dag.addEdge('task1', 'task2');
    dag.addEdge('task2', 'task3');
    dag.addEdge('task4', 'task5');
    dag.addEdge('task5', 'task3');
    const {hasCircle, circlePath} = dag.checkCircle();
    expect(hasCircle).toBe(false);
    expect(circlePath.length).toBe(0);
  });

  /**
   * task1->task2->task3->task4
   * task4->task6
   * task5->task6->task2
   */
  test('test circle check4', () => {
    dag.clear();
    dag.addEdge('task1', 'task2');
    dag.addEdge('task2', 'task3');
    dag.addEdge('task3', 'task4');
    dag.addEdge('task4', 'task6');
    dag.addEdge('task5', 'task6');
    dag.addEdge('task6', 'task2');
    const {hasCircle, circlePath} = dag.checkCircle();
    expect(hasCircle).toBe(true);
    expect(circlePath.join('->')).toEqual('task1->task2->task3->task4->task6->task2');
  });
});
